<template>
  <CDialog
    :title="props.title"
    :descText="props.nodeCode ? `零部件编码：${props.nodeCode}` : ''"
    size="large"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    v-bind="footerBind"
    fixedHeight
  >
    <template #default>
      <el-tabs class="dialog-tabs" v-model="activeTab">
        <el-tab-pane label="零部件BOM" name="BOM" v-if="!props.nodeNo || props.stage">
        </el-tab-pane>
        <el-tab-pane label="场地数据" name="DATA" v-if="!props.stage"> </el-tab-pane>
      </el-tabs>
      <div
        class="site-data-table-wrapper"
        v-show="activeTab === 'BOM'"
        v-if="!props.nodeNo || props.stage"
      >
        <CTable
          :pagination="false"
          :loadData="loadData"
          border
          :extraTableOption="{
            treeConfig: {
              transform: true,
              rowField: 'nodeNo',
              parentField: 'parentNodeNo',
              iconOpen: 'c-mian-xia iconfont',
              iconClose: 'c-mian-you iconfont',
              lazy: true,
              hasChild: 'hasChildren',
              loadMethod({ row }) {
                // 异步加载子节点
                return getListBomTree(
                  props.modelNo,
                  row.nodeNo,
                  props.stage ? props.stage : undefined
                );
              }
            },
            scrollY: { enabled: true },
            height: '100%',
            rowConfig: { height: 56 }
          }"
          cellHeightSize="small"
        >
          <vxe-column title="物料名称/物料编码" min-width="250" show-overflow="tooltip" treeNode>
            <template #default="scope">
              <CTableColumn
                :main-text="scope.row.nodeName"
                :sub-text="scope.row.nodeCode"
              ></CTableColumn>
            </template>
          </vxe-column>
          <vxe-column title="材料类别或牌号" min-width="150" show-overflow="tooltip">
            <template #default="scope">
              {{ empty(scope.row.materialCategory) }}
            </template>
          </vxe-column>
          <vxe-column title="数量" width="150" show-overflow="tooltip">
            <template #default="scope">
              {{ empty(scope.row.quantity) }}
            </template>
          </vxe-column>
          <vxe-column title="单位用量" width="150" show-overflow="tooltip">
            <template #default="scope">
              {{
                scope.row.unit == 'pcs'
                  ? 'pcs'
                  : scope.row.dosage
                  ? scope.row.dosage + scope.row.unit
                  : '-'
              }}
            </template>
          </vxe-column>
          <vxe-column title="备注" width="150" show-overflow="tooltip">
            <template #default="scope">
              {{ empty(scope.row.remark) }}
            </template>
          </vxe-column>
        </CTable>
      </div>
      <div class="site-data-table-wrapper" v-show="activeTab === 'DATA'" v-if="!props.stage">
        <CTable
          :pagination="false"
          :loadData="loadProductionData"
          border
          :extraTableOption="{
            scrollY: { enabled: true },
            height: '100%'
          }"
        >
          <vxe-column title="类型" min-width="200" show-overflow="tooltip">
            <template #default="scope">
              {{
                flowDataTypeMap && scope.row.dataType
                  ? flowDataTypeMap[scope.row.dataType] || scope.row.dataType
                  : '-'
              }}
            </template>
          </vxe-column>
          <vxe-column title="名称" min-width="200" show-overflow="tooltip">
            <template #default="scope">
              {{ empty(scope.row.nodeName) }}
            </template>
          </vxe-column>
          <vxe-column title="用量" width="100" show-overflow="tooltip">
            <template #default="scope">
              {{ scope.row.dosage }}
            </template>
          </vxe-column>
          <vxe-column title="单位" width="100" show-overflow="tooltip">
            <template #default="scope">
              {{ empty(scope.row.unit) }}
            </template>
          </vxe-column>
          <vxe-column title="备注" width="200" show-overflow="tooltip">
            <template #default="scope">
              {{ empty(scope.row.remark) }}
            </template>
          </vxe-column>
        </CTable>
      </div>
    </template>
  </CDialog>
</template>

<script lang="ts" setup name="ReplaceDialog">
import { withDefaults, defineProps, defineEmits, computed, watch, ref } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CTable } from '@/components/CTable';
import { empty } from '@/utils/index';
import { CTableColumn } from '@/components/CTable';
import { getListBomTree, getBomProductionData } from '@/apis/pcf/myModel/modelDetail';
import { getSystemDict } from '@/apis/common/common';
import { uniqWith, isEqual } from 'lodash';

import {
  getSupplierBom,
  getItemListManufacture,
  getSupplierListManufacture,
  getFlowManufacture
} from '@/apis/pcf/supplier/supplierList';

interface ReplaceDialogProps {
  visible: boolean;
  /**
   * 标题（零部件名称、供应商名称）
   */
  title: string;
  /**
   * 模型编码
   */
  modelNo: string;
  /**
   * 节点编码 节点编码存在时，只加载场地数据
   */
  nodeNo?: string;
  /**
   * 零部件编码
   */
  nodeCode: string;
  /**
   * 只读，底部显示我知道了
   */
  readonly?: boolean;
  /**
   * MODEL 子模型查看， SUPPLIER 供应商查看
   */
  type: 'MODEL' | 'SUPPLIER';
  stage?: string; // 阶段
}

const props = withDefaults(defineProps<ReplaceDialogProps>(), {
  readonly: false,
  type: 'MODEL'
});
const emits = defineEmits(['update:visible', 'replace']);

const activeTab = ref('BOM');

const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      if (props.nodeNo && !props.stage) {
        activeTab.value = 'DATA';
      }
      getTypeDict();
    }
  }
);

const loading = ref(false);

function loadData() {
  if (props.type == 'MODEL') {
    return getListBomTree(
      props.modelNo,
      props.stage ? (props?.nodeNo as string) : '-1',
      props.stage ? props.stage : undefined
    ).then(res => {
      return {
        records: res,
        total: res.length
      };
    });
  } else {
    return getSupplierBom(props.modelNo).then(res => {
      return {
        records: res,
        total: res.length
      };
    });
  }
}

function loadProductionData() {
  console.log('type', props.type);
  // BOM清单列表页点击查看的，均取值为nodeNo
  if (props.nodeNo) {
    return getBomProductionData(props.nodeNo).then(res => {
      return {
        records: res.manufactureDataList,
        total: res.manufactureDataList ? res.manufactureDataList.length : 0
      };
    });
  } else {
    if (props.type == 'MODEL') {
      return getItemListManufacture(props.modelNo).then(res => {
        return {
          records: res,
          total: res.length
        };
      });
    } else {
      // 这里的modelNo 传的是formNo
      return getSupplierListManufacture(props.modelNo as string).then(res => {
        return {
          records: res,
          total: res.length
        };
      });
    }
  }
}

function handleConfirm() {
  console.log('handleConfirm');
  if (props.readonly) {
    dialogVisible.value = false;
  } else {
    emits('replace');
  }
}

const footerBind = computed(() => {
  if (props.readonly) {
    return {
      showCancelButton: false,
      confirmText: '我知道了'
    };
  }
  return {
    confirmText: '替换',
    cancelText: '返回'
  };
});

const flowDataTypeMap = ref<Record<string, string>>({});
/**
 * 获取类型和名称 字典
 */
async function getTypeDict() {
  try {
    const res = await getSystemDict('FLOW');

    const uniqOpt = uniqWith(
      res.map(item => {
        return {
          label: item.dataDesc,
          value: item.dataGroup
        };
      }),
      isEqual
    );

    uniqOpt?.forEach(item => {
      flowDataTypeMap.value[item.value] = item.label;
    });
  } catch (error) {
    console.log('error', error);
  }
}
</script>

<style lang="scss" scoped>
.site-data-table-wrapper {
  padding: 0 24px 8px;
  height: calc(100% - 54px);
  :deep(.vxe-table) {
    .vxe-tree--btn-wrapper {
      top: 10px;
      .vxe-tree--node-btn {
        color: #435970 !important;
      }
    }
  }
}
</style>

<style lang="scss">
.dialog-tabs.el-tabs {
  margin-top: -8px;
  --el-tabs-header-height: 48px;
  --el-border-color-light: #f2f3f5;
  .el-tabs__nav-wrap {
    padding-left: 24px;
  }
  .el-tabs__nav-wrap::after {
    height: 1px;
  }
  .el-tabs__item {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #435970;
  }
  .el-tabs__item.is-active {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #0a1f33;
  }
}
</style>
